// ResponsiveFileItem Sony设计风格绘制和动画实现
// 专注于Sony Ive设计语言的视觉效果

#include "responsivefileitem.h"
#include "filestatusiconmanager.h"
#include <QPainter>
#include <QPainterPath>
#include <QLinearGradient>
#include <QRadialGradient>
#include <QFontMetrics>
#include <QApplication>
#include <QStyle>
#include <QDebug>
#include <QtMath>

using namespace SonyIveDesign;

// === Sony设计风格绘制方法实现 ===

void ResponsiveFileItem::drawSonyBackground(QPainter& painter)
{
    QRect rect = this->rect();

    // 使用缓存的背景
    if (!m_cachedBackground.isNull() && !m_backgroundCacheDirty) {
        painter.drawPixmap(rect, m_cachedBackground);
        return;
    }

    // 创建Sony风格渐变背景
    QLinearGradient gradient = SonyColorPalette::createSonyGradient(rect, m_isSelected, m_isHovered);

    // 绘制圆角矩形背景
    QPainterPath path;
    int borderRadius = m_layoutMetricsCached ? m_layoutMetrics.borderRadius : DesignConstants::BORDER_RADIUS;
    path.addRoundedRect(rect.adjusted(1, 1, -1, -1), borderRadius, borderRadius);

    painter.fillPath(path, QBrush(gradient));

    // 绘制边框
    if (m_isSelected || m_isHovered) {
        QPen borderPen(SonyColorPalette::getBorderColor(m_isSelected, m_isHovered ? 0.6 : 0.8), 1);
        painter.setPen(borderPen);
        painter.drawPath(path);
    }

    // 按压效果
    if (m_isPressed) {
        painter.fillPath(path, QColor(0, 0, 0, 20));
    }
}

void ResponsiveFileItem::drawAdaptiveIcon(QPainter& painter)
{
    QRect iconRect = getIconRect();
    if (iconRect.isEmpty()) return;

    // 获取文件类型图标
    QIcon fileIcon;
    if (m_fileInfo.fileType == FileType::PDF) {
        fileIcon = QApplication::style()->standardIcon(QStyle::SP_FileIcon);
    } else {
        fileIcon = QApplication::style()->standardIcon(QStyle::SP_FileIcon);
    }

    // 根据状态调整图标透明度
    double iconOpacity = 1.0;
    if (m_fileInfo.processStatus == FileProcessStatus::Processing) {
        iconOpacity = 0.7 + 0.3 * qSin(QTime::currentTime().msec() * 0.01);
    } else if (m_fileInfo.processStatus == FileProcessStatus::Error) {
        iconOpacity = 0.5;
    }

    painter.setOpacity(iconOpacity * m_animationOpacity);
    fileIcon.paint(&painter, iconRect, Qt::AlignCenter);
    painter.setOpacity(m_animationOpacity);
}

void ResponsiveFileItem::drawAdaptiveText(QPainter& painter)
{
    QRect textRect = getTextRect();
    if (textRect.isEmpty()) return;

    // 获取布局度量
    if (!m_layoutMetricsCached) {
        m_layoutMetrics.updateForMode(m_displayMode);
        m_layoutMetricsCached = true;
    }

    painter.setFont(m_layoutMetrics.primaryFont);

    // 主文本颜色
    QColor textColor = SonyColorPalette::getTextColor(true, m_isSelected ? 1.0 : 0.9);
    painter.setPen(textColor);

    // 获取自适应文件名
    QString displayText = getAdaptiveFileName();

    // 绘制文件名
    QFontMetrics fm(m_layoutMetrics.primaryFont);
    QRect textBounds = fm.boundingRect(textRect, Qt::AlignLeft | Qt::AlignVCenter, displayText);

    painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, displayText);

    // 在Standard及以上模式显示页码信息
    if (m_displayMode >= DisplayMode::Standard && m_fileInfo.pageCount > 1) {
        QString pageText = getPageCountText();
        if (!pageText.isEmpty()) {
            painter.setFont(m_layoutMetrics.secondaryFont);
            painter.setPen(SonyColorPalette::getTextColor(false, 0.7));

            QRect pageRect = textRect;
            pageRect.setTop(textBounds.bottom() + 2);
            painter.drawText(pageRect, Qt::AlignLeft | Qt::AlignTop, pageText);
        }
    }
}

void ResponsiveFileItem::drawProgressIndicator(QPainter& painter)
{
    if (m_displayMode < DisplayMode::Standard) return;

    QRect progressRect = getProgressRect();
    if (progressRect.isEmpty() || m_fileInfo.progress <= 0) return;

    // Sony风格圆角进度条
    int radius = 2;
    QPainterPath backgroundPath;
    backgroundPath.addRoundedRect(progressRect, radius, radius);

    // 进度条背景
    painter.fillPath(backgroundPath, QColor(200, 200, 200, 100));

    // 进度条填充
    if (m_fileInfo.progress > 0) {
        QRect fillRect = progressRect;
        fillRect.setWidth(progressRect.width() * m_fileInfo.progress / 100);

        QPainterPath fillPath;
        fillPath.addRoundedRect(fillRect, radius, radius);

        // 根据状态设置颜色
        QColor progressColor = SonyColorPalette::getStatusColor(m_fileInfo.processStatus, 0.8);

        // Sony风格渐变填充
        QLinearGradient progressGradient(fillRect.topLeft(), fillRect.bottomLeft());
        progressGradient.setColorAt(0.0, progressColor.lighter(120));
        progressGradient.setColorAt(1.0, progressColor);

        painter.fillPath(fillPath, QBrush(progressGradient));
    }
}

void ResponsiveFileItem::drawStatusBadge(QPainter& painter)
{
    if (m_displayMode < DisplayMode::Compact) return;

    QRect badgeRect = getStatusBadgeRect();
    if (badgeRect.isEmpty()) return;

    // 状态图标
    QIcon statusIcon;
    switch (m_fileInfo.processStatus) {
        case FileProcessStatus::Processing:
            statusIcon = FileStatusIconManager::getIcon(FileStatusIconManager::FileStatus::Processing);
            break;
        case FileProcessStatus::Completed:
            statusIcon = FileStatusIconManager::getIcon(FileStatusIconManager::FileStatus::Completed);
            break;
        case FileProcessStatus::Error:
            statusIcon = FileStatusIconManager::getIcon(FileStatusIconManager::FileStatus::Error);
            break;
        default:
            statusIcon = FileStatusIconManager::getIcon(FileStatusIconManager::FileStatus::Queued);
            break;
    }

    if (!statusIcon.isNull()) {
        // Sony风格状态徽章背景
        QColor badgeColor = SonyColorPalette::getStatusColor(m_fileInfo.processStatus, 0.2);

        QPainterPath badgePath;
        badgePath.addEllipse(badgeRect);
        painter.fillPath(badgePath, badgeColor);

        // 绘制状态图标
        painter.setOpacity(0.8 * m_animationOpacity);
        statusIcon.paint(&painter, badgeRect.adjusted(2, 2, -2, -2), Qt::AlignCenter);
        painter.setOpacity(m_animationOpacity);
    }
}

void ResponsiveFileItem::drawLayoutModeIndicator(QPainter& painter)
{
    if (m_displayMode < DisplayMode::Expanded) return;

    QString layoutText = getLayoutModeText();
    if (layoutText.isEmpty()) return;

    QRect layoutRect = getLayoutModeRect();
    if (layoutRect.isEmpty()) return;

    // Sony风格布局模式指示器
    painter.setFont(m_layoutMetrics.secondaryFont);
    painter.setPen(SonyColorPalette::getTextColor(false, 0.6));

    // 绘制布局模式文本
    painter.drawText(layoutRect, Qt::AlignCenter, layoutText);
}

void ResponsiveFileItem::drawSelectionOverlay(QPainter& painter)
{
    if (!m_isSelected) return;

    QRect rect = this->rect();

    // Sony风格选择覆盖层
    QLinearGradient selectionGradient(rect.topLeft(), rect.bottomLeft());
    selectionGradient.setColorAt(0.0, QColor(64, 128, 255, 30));
    selectionGradient.setColorAt(1.0, QColor(96, 144, 255, 20));

    QPainterPath selectionPath;
    int borderRadius = m_layoutMetricsCached ? m_layoutMetrics.borderRadius : DesignConstants::BORDER_RADIUS;
    selectionPath.addRoundedRect(rect.adjusted(1, 1, -1, -1), borderRadius, borderRadius);

    painter.fillPath(selectionPath, QBrush(selectionGradient));

    // 选择边框
    QPen selectionPen(QColor(64, 128, 255, 180), 2);
    painter.setPen(selectionPen);
    painter.drawPath(selectionPath);
}

// === 智能文本处理实现 ===

QString ResponsiveFileItem::getAdaptiveFileName() const
{
    QString fileName = m_fileInfo.fileName;

    // 根据显示模式调整文件名显示
    switch (m_displayMode) {
        case DisplayMode::Micro:
            return AdaptiveTextProcessor::getFileNameWithoutExtension(fileName, m_displayMode);
        case DisplayMode::Compact:
            return AdaptiveTextProcessor::getFileNameWithoutExtension(fileName, m_displayMode);
        default:
            return fileName;
    }
}

QString ResponsiveFileItem::getStatusText() const
{
    if (!m_fileInfo.statusText.isEmpty()) {
        return m_fileInfo.statusText;
    }

    return UnifiedFileInfo::processStatusToString(m_fileInfo.processStatus);
}

QString ResponsiveFileItem::getLayoutModeText() const
{
    return UnifiedFileInfo::layoutModeToString(m_fileInfo.layoutMode);
}

QString ResponsiveFileItem::getPageCountText() const
{
    if (m_fileInfo.pageCount <= 1) {
        return QString();
    }

    if (m_displayMode >= DisplayMode::Full) {
        return QString("%1 页").arg(m_fileInfo.pageCount);
    } else {
        return QString::number(m_fileInfo.pageCount);
    }
}

// === 布局计算实现 ===

QRect ResponsiveFileItem::getIconRect() const
{
    if (!m_layoutMetricsCached) {
        m_layoutMetrics.updateForMode(m_displayMode);
        m_layoutMetricsCached = true;
    }

    QRect rect = this->rect();
    int iconSize = m_layoutMetrics.iconSize;
    int padding = m_layoutMetrics.padding;

    return QRect(padding, (rect.height() - iconSize) / 2, iconSize, iconSize);
}

QRect ResponsiveFileItem::getTextRect() const
{
    if (!m_layoutMetricsCached) {
        m_layoutMetrics.updateForMode(m_displayMode);
        m_layoutMetricsCached = true;
    }

    QRect iconRect = getIconRect();
    QRect rect = this->rect();
    int spacing = m_layoutMetrics.spacing;
    int padding = m_layoutMetrics.padding;

    int left = iconRect.right() + spacing;
    int right = rect.right() - padding;

    // 为状态徽章和其他元素留出空间
    if (m_displayMode >= DisplayMode::Compact) {
        right -= 24; // 状态徽章空间
    }
    if (m_displayMode >= DisplayMode::Expanded) {
        right -= 40; // 布局模式指示器空间
    }

    return QRect(left, rect.top() + padding, right - left, rect.height() - 2 * padding);
}

QRect ResponsiveFileItem::getProgressRect() const
{
    if (m_displayMode < DisplayMode::Standard) {
        return QRect();
    }

    QRect textRect = getTextRect();
    return QRect(textRect.left(), textRect.bottom() - 6, textRect.width(), 4);
}

QRect ResponsiveFileItem::getStatusBadgeRect() const
{
    if (m_displayMode < DisplayMode::Compact) {
        return QRect();
    }

    QRect rect = this->rect();
    int size = 16;
    int padding = m_layoutMetricsCached ? m_layoutMetrics.padding : DesignConstants::SPACING_NORMAL;

    return QRect(rect.right() - padding - size,
                (rect.height() - size) / 2,
                size, size);
}

QRect ResponsiveFileItem::getLayoutModeRect() const
{
    if (m_displayMode < DisplayMode::Expanded) {
        return QRect();
    }

    QRect rect = this->rect();
    QRect statusRect = getStatusBadgeRect();
    int padding = m_layoutMetricsCached ? m_layoutMetrics.padding : DesignConstants::SPACING_NORMAL;

    return QRect(statusRect.left() - 40, statusRect.top(), 35, statusRect.height());
}

// === 动画系统实现 ===

void ResponsiveFileItem::initializeAnimations()
{
    // 悬停动画
    m_hoverAnimation = new QPropertyAnimation(this, "hoverScale", this);
    m_hoverAnimation->setDuration(DesignConstants::ANIMATION_DURATION_FAST);
    m_hoverAnimation->setEasingCurve(QEasingCurve::OutCubic);
    connect(m_hoverAnimation, &QPropertyAnimation::finished,
            this, &ResponsiveFileItem::onHoverAnimationFinished);

    // 选择动画
    m_selectionAnimation = new QPropertyAnimation(this, "selectionScale", this);
    m_selectionAnimation->setDuration(DesignConstants::ANIMATION_DURATION_NORMAL);
    m_selectionAnimation->setEasingCurve(QEasingCurve::OutCubic);
    connect(m_selectionAnimation, &QPropertyAnimation::finished,
            this, &ResponsiveFileItem::onSelectionAnimationFinished);

    // 透明度动画
    m_opacityAnimation = new QPropertyAnimation(this, "animationOpacity", this);
    m_opacityAnimation->setDuration(DesignConstants::ANIMATION_DURATION_NORMAL);
    m_opacityAnimation->setEasingCurve(QEasingCurve::OutCubic);
}

void ResponsiveFileItem::animateHover(bool isEntering)
{
    if (m_performanceMode) return;

    double targetScale = isEntering ? DesignConstants::HOVER_SCALE : 1.0;

    if (m_hoverAnimation->state() == QPropertyAnimation::Running) {
        m_hoverAnimation->stop();
    }

    m_hoverAnimation->setStartValue(m_hoverScale);
    m_hoverAnimation->setEndValue(targetScale);
    m_hoverAnimation->start();

}

void ResponsiveFileItem::animateSelection(bool isSelecting)
{
    if (m_performanceMode) return;

    double targetScale = isSelecting ? DesignConstants::SELECTION_SCALE : 1.0;

    if (m_selectionAnimation->state() == QPropertyAnimation::Running) {
        m_selectionAnimation->stop();
    }

    m_selectionAnimation->setStartValue(m_selectionScale);
    m_selectionAnimation->setEndValue(targetScale);
    m_selectionAnimation->start();

    m_backgroundCacheDirty = true;
    update();

}

void ResponsiveFileItem::animateModeTransition()
{
    if (m_performanceMode) return;

    // 模式切换时的淡入淡出效果
    if (m_opacityAnimation->state() == QPropertyAnimation::Running) {
        m_opacityAnimation->stop();
    }

    m_opacityAnimation->setStartValue(m_animationOpacity);
    m_opacityAnimation->setEndValue(0.3);
    m_opacityAnimation->setDuration(DesignConstants::ANIMATION_DURATION_FAST);

    connect(m_opacityAnimation, &QPropertyAnimation::finished, this, [this]() {
        // 淡出完成后淡入
        m_opacityAnimation->setStartValue(0.3);
        m_opacityAnimation->setEndValue(1.0);
        m_opacityAnimation->start();
        update();
    }, Qt::UniqueConnection);

    m_opacityAnimation->start();
    update();
}

// === 视觉效果实现 ===

void ResponsiveFileItem::updateDropShadow()
{
    if (!shouldUseComplexEffects()) {
        if (m_dropShadowEffect) {
            setGraphicsEffect(nullptr);
            m_dropShadowEffect = nullptr;
        }
        return;
    }

    if (!m_dropShadowEffect) {
        m_dropShadowEffect = new QGraphicsDropShadowEffect(this);
        m_dropShadowEffect->setBlurRadius(DesignConstants::SHADOW_BLUR_RADIUS);
        m_dropShadowEffect->setOffset(DesignConstants::SHADOW_OFFSET, DesignConstants::SHADOW_OFFSET);
        m_dropShadowEffect->setColor(SonyColorPalette::getShadowColor(0.3));
        setGraphicsEffect(m_dropShadowEffect);
    }

    // 根据状态调整阴影
    if (m_isHovered) {
        m_dropShadowEffect->setBlurRadius(DesignConstants::SHADOW_BLUR_RADIUS + 4);
        m_dropShadowEffect->setColor(SonyColorPalette::getShadowColor(0.4));
    } else {
        m_dropShadowEffect->setBlurRadius(DesignConstants::SHADOW_BLUR_RADIUS);
        m_dropShadowEffect->setColor(SonyColorPalette::getShadowColor(0.2));
    }
}

void ResponsiveFileItem::updateBackgroundCache()
{
    if (m_engine) {
        m_cachedBackground = m_engine->createSonyBackgroundTexture(
            this->size(), m_isSelected, m_isHovered);
    }

    m_backgroundCacheDirty = false;
    update();
}

QPixmap ResponsiveFileItem::createCachedBackground()
{
    QSize size = this->size();
    if (size.isEmpty()) {
        return QPixmap();
    }

    QPixmap pixmap(size);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制背景到缓存
    QRect rect(0, 0, size.width(), size.height());
    QLinearGradient gradient = SonyColorPalette::createSonyGradient(rect, m_isSelected, m_isHovered);

    QPainterPath path;
    int borderRadius = m_layoutMetricsCached ? m_layoutMetrics.borderRadius : DesignConstants::BORDER_RADIUS;
    path.addRoundedRect(rect.adjusted(1, 1, -1, -1), borderRadius, borderRadius);

    painter.fillPath(path, QBrush(gradient));

    return pixmap;
}

// === 性能优化实现 ===

void ResponsiveFileItem::enablePerformanceMode(bool enabled)
{
    if (m_performanceMode != enabled) {
        m_performanceMode = enabled;

        if (enabled) {
            // 禁用复杂效果
            setGraphicsEffect(nullptr);
            m_dropShadowEffect = nullptr;

            // 停止所有动画
            if (m_hoverAnimation) m_hoverAnimation->stop();
            if (m_selectionAnimation) m_selectionAnimation->stop();
            if (m_opacityAnimation) m_opacityAnimation->stop();
        } else {
            // 重新启用效果
            updateDropShadow();
        }

    }
}

bool ResponsiveFileItem::shouldUseComplexEffects() const
{
    return !m_performanceMode &&
           (m_displayMode >= DisplayMode::Standard) &&
           QApplication::instance()->property("enableComplexEffects").toBool();
}